<template>
  <a-card style="width: 100%; height: 100%">
    <div
      ref="UserTypeRef"
      id="userType"
      style="width: 100%; height: 360px"
    ></div>
  </a-card>
</template>
  
<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";

const UserTypeRef = ref("");

const generateRandomData = () => {
  const userType = "用户";
  const anonymousType = "匿名用户";

  // 随机生成用户和匿名用户的占比，确保总和为100%
  const userRatio = Math.floor(Math.random() * 100);
  const anonymousRatio = 100 - userRatio; // 匿名用户占比

  return [
    { value: userRatio, name: userType },
    { value: anonymousRatio, name: anonymousType },
  ];
};

onMounted(() => {
  const chartDom = document.getElementById("userType");
  const myChart = echarts.init(chartDom);

  // 生成随机数据
  const data = generateRandomData();

  const option = {
    title: {
      text: "用户类型占比",
      subtext: "随机生成数据",
      left: "center",
    },
    tooltip: {
      trigger: "item",
    },
    legend: {
      orient: "vertical",
      left: "left",
    },
    series: [
      {
        name: "用户类型",
        type: "pie",
        radius: "50%",
        data: data, // 使用随机生成的数据
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };

  myChart.setOption(option);

  // 监听窗口尺寸变化，调整图表大小
  window.addEventListener("resize", () => myChart.resize());
});

// 清理事件监听器
onBeforeUnmount(() => {
  window.removeEventListener("resize", () => myChart.resize());
});
</script>
  
  <style lang="scss" scoped>
</style>
  